import { GroupModel } from '../models/Group';
import { WebsiteModel } from '../models/Website';
import { 
  Group, 
  CreateGroupRequest, 
  UpdateGroupRequest, 
  GroupWithWebsites,
  ApiResponse 
} from '../types/group';

export class GroupService {
  // 获取所有分组
  static async getAllGroups(): Promise<ApiResponse<Group[]>> {
    try {
      const groups = await GroupModel.findAll();
      return {
        success: true,
        message: '获取分组列表成功',
        data: groups
      };
    } catch (error) {
      return {
        success: false,
        message: '获取分组列表失败'
      };
    }
  }

  // 获取分组详情（包含网站列表）
  static async getGroupById(id: string): Promise<ApiResponse<GroupWithWebsites>> {
    try {
      const group = await GroupModel.findById(id);
      if (!group) {
        return {
          success: false,
          message: '分组不存在'
        };
      }

      const websites = await WebsiteModel.findByGroupId(id);
      const groupWithWebsites: GroupWithWebsites = {
        ...group,
        websites
      };

      return {
        success: true,
        message: '获取分组详情成功',
        data: groupWithWebsites
      };
    } catch (error) {
      return {
        success: false,
        message: '获取分组详情失败'
      };
    }
  }

  // 获取所有分组及其网站
  static async getAllGroupsWithWebsites(): Promise<ApiResponse<GroupWithWebsites[]>> {
    try {
      const groups = await GroupModel.findAll();
      const groupsWithWebsites: GroupWithWebsites[] = [];

      for (const group of groups) {
        const websites = await WebsiteModel.findByGroupId(group.id);
        groupsWithWebsites.push({
          ...group,
          websites
        });
      }

      return {
        success: true,
        message: '获取分组和网站列表成功',
        data: groupsWithWebsites
      };
    } catch (error) {
      return {
        success: false,
        message: '获取分组和网站列表失败'
      };
    }
  }

  // 创建分组
  static async createGroup(data: CreateGroupRequest): Promise<ApiResponse<Group>> {
    try {
      // 验证分组名称
      if (!data.name || data.name.trim().length === 0) {
        return {
          success: false,
          message: '分组名称不能为空'
        };
      }

      // 检查分组名称是否已存在
      const exists = await GroupModel.existsByName(data.name.trim());
      if (exists) {
        return {
          success: false,
          message: '分组名称已存在'
        };
      }

      const group = await GroupModel.create({
        ...data,
        name: data.name.trim()
      });

      return {
        success: true,
        message: '创建分组成功',
        data: group
      };
    } catch (error) {
      return {
        success: false,
        message: '创建分组失败'
      };
    }
  }

  // 更新分组
  static async updateGroup(id: string, data: UpdateGroupRequest): Promise<ApiResponse<Group>> {
    try {
      // 检查分组是否存在
      const existingGroup = await GroupModel.findById(id);
      if (!existingGroup) {
        return {
          success: false,
          message: '分组不存在'
        };
      }

      // 如果更新名称，检查是否重复
      if (data.name) {
        const trimmedName = data.name.trim();
        if (trimmedName.length === 0) {
          return {
            success: false,
            message: '分组名称不能为空'
          };
        }

        const exists = await GroupModel.existsByName(trimmedName, id);
        if (exists) {
          return {
            success: false,
            message: '分组名称已存在'
          };
        }

        data.name = trimmedName;
      }

      const updatedGroup = await GroupModel.update(id, data);
      if (!updatedGroup) {
        return {
          success: false,
          message: '更新分组失败'
        };
      }

      return {
        success: true,
        message: '更新分组成功',
        data: updatedGroup
      };
    } catch (error) {
      return {
        success: false,
        message: '更新分组失败'
      };
    }
  }

  // 删除分组
  static async deleteGroup(id: string): Promise<ApiResponse<void>> {
    try {
      // 检查分组是否存在
      const existingGroup = await GroupModel.findById(id);
      if (!existingGroup) {
        return {
          success: false,
          message: '分组不存在'
        };
      }

      // 检查分组下是否有网站
      const websiteCount = await WebsiteModel.countByGroupId(id);
      if (websiteCount > 0) {
        return {
          success: false,
          message: `无法删除分组，该分组下还有 ${websiteCount} 个网站`
        };
      }

      const deleted = await GroupModel.delete(id);
      if (!deleted) {
        return {
          success: false,
          message: '删除分组失败'
        };
      }

      return {
        success: true,
        message: '删除分组成功'
      };
    } catch (error) {
      return {
        success: false,
        message: '删除分组失败'
      };
    }
  }

  // 强制删除分组（同时删除分组下的所有网站）
  static async forceDeleteGroup(id: string): Promise<ApiResponse<{ deletedWebsites: number }>> {
    try {
      // 检查分组是否存在
      const existingGroup = await GroupModel.findById(id);
      if (!existingGroup) {
        return {
          success: false,
          message: '分组不存在'
        };
      }

      // 删除分组下的所有网站
      const deletedWebsites = await WebsiteModel.deleteByGroupId(id);

      // 删除分组
      const deleted = await GroupModel.delete(id);
      if (!deleted) {
        return {
          success: false,
          message: '删除分组失败'
        };
      }

      return {
        success: true,
        message: `删除分组成功，同时删除了 ${deletedWebsites} 个网站`,
        data: { deletedWebsites }
      };
    } catch (error) {
      return {
        success: false,
        message: '删除分组失败'
      };
    }
  }

  // 重新排序分组
  static async reorderGroups(groupOrders: { id: string; order: number }[]): Promise<ApiResponse<void>> {
    try {
      // 验证所有分组是否存在
      for (const { id } of groupOrders) {
        const group = await GroupModel.findById(id);
        if (!group) {
          return {
            success: false,
            message: `分组 ${id} 不存在`
          };
        }
      }

      await GroupModel.reorder(groupOrders);

      return {
        success: true,
        message: '分组排序更新成功'
      };
    } catch (error) {
      return {
        success: false,
        message: '分组排序更新失败'
      };
    }
  }
}